package com.sloera.thread;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 集合类不安全的问题
 *
 * @author sloera
 * @create 2020/4/25
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
        //listNotSafe();
        //setNotSafe();
        Map<String, String> map = new ConcurrentHashMap<>();
        //TODO ConcurrentHashMap与HashMap底层的不同
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i + 1)).start();
        }
    }

    public static void setNotSafe() {
        //Set<String> set = new HashSet<>();
        //Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet<>(); //底层是CopyOnWriteArrayList
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i + 1)).start();
        }
    }

    public static void listNotSafe() {
        //List<String> list = Arrays.asList("a", "b", "c");
        //list.forEach(System.out::println);
        //List<String> list = new Vector<>();
        //List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();
        /*list.add("a");
        list.add("b");
        list.add("c");
        for (String element : list) {
            System.out.println(element);
        }*/
        //java.util.ConcurrentModificationException 线程不安全在高并发下常见的异常
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i + 1)).start();
        }
    }
}
